// 智能锁列表
import debounce from "debounce";
import * as MSroomAPI from "../../api/interfaces/MSroom";
import { HttpHandler } from "../../api/handle/httpHandler";
import { AES_Encrypt } from "../../utils/crypto";
import * as EKeyAPI from "../../api/interfaces/key";

Page({
  data: {
    isReady: false, // 页面数据是否已准备好
    keyList: new Array<IEKeyAPI.List.EKeyInfo>(), // 电子钥匙列表
    currentPageNo: 1,
    hotelName: "乐住精品酒店", //酒店名称
    hotelAddress: "正商经开广场2号楼", //酒店地址
    hotelNo: "测试门牌号", //酒店门牌号
    name: "", // 用户名
    phone: "", // 手机号
    roomType: "豪华大床房", //房型
    roomNo: "", //房间门牌号
    roomId: "", //房间ID
    startTime: '2025-08-01',
    endTime: '2025-08-02',
    roomList: [],
    roomListIndex: 0
  },
  onLoad(opt) {
    if (opt.scene) {
      this.getRoomInfo(opt.scene)
    }
    const eventChannel = this.getOpenerEventChannel();
    this.eventChannel = eventChannel
    eventChannel.on('roomInfo', (data) => {
      this.setData({ roomInfo: data.item });
      MSroomAPI.getToken().then(res => {
        if (res.code == 200) {
          wx.removeStorageSync("access_token"); // 清空当前用户保存的登录状态
          wx.setStorageSync("access_token", AES_Encrypt(res.result));
        }
      })
    });



    // this.modifyKeyList();
  },

  onShow() {
    if (!wx.getStorageSync('token')) {
      wx.showToast({
        title: '请先登录'
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/userLogin/userLogin',
          icon:'none'
        })
      }, 1000)
    }

    // wx.showLoading({ title: "" });
    // this.roomAxiosList();
  },

  /* TODO 处理用户错误日志, 用户可自行操作日志上传 */
  handleShowLog(...args: any) {
    console.log("操作日志:", ...args);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.modifyKeyList();
  },
  getRoomInfo(roomId) {
    MSroomAPI.getRoomById({
      roomId: roomId
    }).then(res => {
      console.log(res.result.records[0]);

      if (res.result) {
        // this.setData({ this.data.roomNo: res.result.roomNo });

        this.setData({ roomInfo: res.result.records[0] });


      }
    })
  },
  onReachBottom() {
    this.modifyKeyList(this.data.currentPageNo + 1);
  },
  // 获取房间
  roomAxiosList() {
    MSroomAPI.allRoom().then(res => {

      if (res.result) {

        this.setData({ roomList: res.result, roomNo: res.result[0].roomNo, roomId: res.result[0].id });

      }
    })
    MSroomAPI.getToken().then(res => {
      if (res.code == 200) {
        wx.removeStorageSync("access_token"); // 清空当前用户保存的登录状态
        wx.setStorageSync("access_token", AES_Encrypt(res.result));
      }
    })
  },
  bindDateChange: function (e) {
    this.setData({
      startTime: e.detail.value
    })
  },
  bindDateChange2: function (e) {
    this.setData({
      endTime: e.detail.value
    })
  },
  bindPickerChange(e) {

    this.setData({ roomListIndex: e.detail.value, roomNo: this.data.roomList[e.detail.value].roomNo, roomId: this.data.roomList[e.detail.value].id });
  },
  /* 更新电子钥匙列表 */
  modifyKeyList: debounce(function (pageNo: number = 1) {
    EKeyAPI.list({
      pageNo: pageNo,
      pageSize: 20
    }).then(res => {
      if (HttpHandler.isResponseTrue(res)) {
        if (pageNo == 1) this.data.keyList.splice(0, this.data.keyList.length, ...res.list);
        else res.list.forEach(item => this.data.keyList.push(item));
        this.setData({ keyList: this.data.keyList, currentPageNo: pageNo });
        wx.stopPullDownRefresh();
      } else {
        wx.removeStorageSync("access_token");
        HttpHandler.handleResponseError(res);
        wx.reLaunch({ url: "/pages/login/login" });
      }
      wx.hideLoading();
    }).catch(err => {
      wx.removeStorageSync("access_token");
      HttpHandler.handleServerError(err);
      wx.reLaunch({ url: "/pages/login/login" });
      wx.hideLoading();
    })
  }, 100),

  /* 退出登录 */
  handleLogOut: debounce(function () {
    wx.showLoading({ title: "退出登录" });
    wx.removeStorageSync("access_token");
    wx.removeStorageSync("user_psd");
    wx.reLaunch({ url: "/pages/login/login", complete: () => { wx.hideLoading(); } });
  }, 100),

  // 进入锁详情页
  toDetail(event) {
    const keyItem = JSON.stringify(event.target.dataset.value);
    wx.setStorageSync("keyInfo", keyItem);
    wx.navigateTo({
      url: "../lockBase/lockBase"
    })
  },
  skip() {

    let data = {
      hotelName: this.data.roomInfo.bindHotel_dictText, //酒店名称
      // hotelAddress: this.roomInfo.hotelAddress, //酒店地址
      hotelNo: this.data.hotelNo, //酒店门牌号
      name: this.data.name, // 用户名
      phone: this.data.phone, // 手机号
      roomType: this.data.roomInfo.type_dictText, //房型
      roomNo: this.data.roomInfo.roomNo, //房间门牌号
      roomId: this.data.roomInfo.id,//房间ID
      startTime: this.data.startTime,
      endTime: this.data.endTime,
      hotelId: this.data.roomInfo.bindHotel
    }

    MSroomAPI.placeOrder(data).then(res => {
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      });
      if (res.code == 200) {
        if (res.result.status == 'NOT_CHECK') {
          setTimeout(() => {
            wx.navigateTo({
              url: "../authentication/authentication?orderNo=" + res.result.orderNo + '&name=' + this.data.name,
            })
          }, 1000);
        }
      }
    })
  }
})